# import requests
# import os
#
# save_folder = 'downloaded_images'
# # download_and_save_image(image_url)
# def download_and_save_image(url):
#     try:
#         # 发送请求获取图片内容
#         response = requests.get(url)
#         # 检查响应状态码
#         if response.status_code == 200:
#             # 从 URL 中提取文件名
#             filename = os.path.join(save_folder, url.split("/")[-1])
#             # 确保保存文件夹存在
#             if not os.path.exists(save_folder):
#                 os.makedirs(save_folder)
#             # 以二进制写入模式打开文件并保存图片内容
#             with open(filename, 'wb') as file:
#                 file.write(response.content)
#             print(f"图片 {filename} 保存成功")
#             return True
#         else:
#             print(f"请求失败，状态码: {response.status_code}")
#     except requests.RequestException as e:
#         print(f"请求过程中出现错误: {e}")
#     except Exception as e:
#         print(f"保存图片时出现错误: {e}")
#




import requests
import zipfile
import os

# # 图片链接列表
# image_urls = [
#     'https://wx2.sinaimg.cn/large/006OUNpHly1hyd9eko7c9j32803y84qv.jpg',
#     'https://wx4.sinaimg.cn/large/006OUNpHly1hwkkk3h4xvj30u01hcdj5.jpg'
# ]
#
# # 指定的文件夹路径
# target_folder = 'downloaded_images'
# headers = {
#     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
#     'referer': 'https://cggm.r48zr.net/',
#     'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
#     'authority': 'tju.7pzzv.us',
#     'accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
# }

def downloadImage(image_urls, name,headers):
    target_folder = f'E:/reptilePic/{name}'
    # 如果文件夹不存在，创建它
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)

    # 下载图片并保存到指定文件夹
    for url in image_urls:
        try:
            response = requests.get(url)
            response.raise_for_status()  # 检查请求是否成功
            file_name = url.split('/')[-1]  # 从URL中提取文件名
            if 'webp' in file_name:
                file_name = file_name.replace("webp", "jpg")
            print(f"正在下载: {file_name}")
            file_path = os.path.join(target_folder, file_name)
            with open(file_path, 'wb') as file:
                file.write(response.content)
                print(f"图片保存成功:{file_path}")

        except requests.RequestException as e:
            print(f"下载失败: {e}")
            return None
    result = {'message': f'图片保存成功'}
    return result

    # # 创建ZIP文件并将图片添加到其中
    # zip_file_path = os.path.join(target_folder, 'images.zip')
    # with zipfile.ZipFile(zip_file_path, 'w') as zipf:
    #     for root, dirs, files in os.walk(target_folder):
    #         for file in files:
    #             file_path = os.path.join(root, file)
    #             zipf.write(file_path)
    #
    # print(f"已将图片打包成 {zip_file_path}")